<template>
  <div class="announcement-list-container">
    <div class="header">
      <h2>公告管理</h2>
      <div class="actions">
        <el-input
          v-model="searchQuery"
          placeholder="搜索公告..."
          :prefix-icon="Search"
          clearable
          @clear="handleSearch"
          @input="handleSearch"
          class="search-input"
        />
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>添加公告
        </el-button>
      </div>
    </div>

    <el-table
      v-loading="loading"
      :data="announcementList"
      border
      style="width: 100%"
    >
      <el-table-column type="expand">
        <template #default="props">
          <div class="announcement-detail">
            <div class="detail-section">
              <h4>公告内容</h4>
              <div class="detail-item" v-html="formatContent(props.row.content)"></div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip />
      <el-table-column label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createdTime) }}
        </template>
      </el-table-column>
      <el-table-column label="更新时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.updatedTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="160">
        <template #default="{ row }">
          <el-button-group>
            <el-button type="primary" @click="handleEdit(row)" :icon="Edit" size="small">
              编辑
            </el-button>
            <el-button type="danger" @click="handleDelete(row)" :icon="Delete" size="small">
              删除
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      :current-page="currentPage"
      :page-size="pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      @update:current-page="currentPage = $event"
      @update:page-size="pageSize = $event"
      class="pagination"
    />

    <!-- 公告表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加公告' : '编辑公告'"
      width="700px"
    >
      <el-form
        ref="announcementFormRef"
        :model="announcementForm"
        :rules="announcementRules"
        label-width="100px"
      >
        <el-form-item label="公告标题" prop="title">
          <el-input v-model="announcementForm.title" placeholder="请输入公告标题" />
        </el-form-item>
        <el-form-item label="公告内容" prop="content">
          <el-input
            v-model="announcementForm.content"
            type="textarea"
            :rows="8"
            placeholder="请输入公告内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, Plus, Edit, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

// 状态变量
const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const dialogType = ref('add')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchQuery = ref('')
const announcementList = ref([])

// 表单相关
const announcementFormRef = ref(null)
const announcementForm = reactive({
  title: '',
  content: ''
})

// 表单验证规则
const announcementRules = {
  title: [
    { required: true, message: '请输入公告标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度必须在2到100个字符之间', trigger: 'blur' }
  ],
  content: [
    { required: false, message: '请输入公告内容', trigger: 'blur' }
  ]
}

// 防抖函数
const debounce = (fn, delay) => {
  let timer = null
  return (...args) => {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}

// 获取公告列表
const fetchAnnouncements = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      search: searchQuery.value
    }
    await request.get('/announcement/page', params, {
      showDefaultMsg: false,
      onSuccess: (res) => {
        announcementList.value = res.records||[]
        total.value = res.total||0
      }
    })
  } catch (error) {
    console.error('获取公告列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 处理分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchAnnouncements()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchAnnouncements()
}

// 处理搜索
const handleSearch = debounce(() => {
  currentPage.value = 1
  fetchAnnouncements()
}, 300)

// 处理添加公告
const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

// 处理编辑公告
const handleEdit = (row) => {
  dialogType.value = 'edit'
  resetForm()
  Object.assign(announcementForm, {
    id: row.id,
    title: row.title,
    content: row.content
  })
  dialogVisible.value = true
}

// 重置表单
const resetForm = () => {
  announcementForm.id = null
  announcementForm.title = ''
  announcementForm.content = ''
}

// 处理删除公告
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除该公告吗？此操作不可恢复。',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await request.delete(`/announcement/${row.id}`, {
        successMsg: '删除成功'
      })
      fetchAnnouncements()
    } catch (error) {
      console.error('删除公告失败:', error)
    }
  })
}

// 处理表单提交
const handleSubmit = () => {
  announcementFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        if (dialogType.value === 'add') {
          await request.post('/announcement', announcementForm, {
            successMsg: '添加成功'
          })
        } else {
          await request.put(`/announcement/${announcementForm.id}`, announcementForm, {
            successMsg: '更新成功'
          })
        }
        dialogVisible.value = false
        fetchAnnouncements()
      } catch (error) {
        console.error('保存公告失败:', error)
      } finally {
        submitting.value = false
      }
    }
  })
}

// 格式化内容 (将换行符转换为<br>)
const formatContent = (content) => {
  if (!content) return ''
  return content.replace(/\n/g, '<br>')
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '暂无'
  return new Date(date).toLocaleString()
}

// 初始化
onMounted(() => {
  fetchAnnouncements()
})
</script>

<style lang="scss" scoped>
.announcement-list-container {
  padding: 20px;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      font-size: 24px;
      color: var(--el-text-color-primary);
    }

    .actions {
      display: flex;
      gap: 10px;

      .search-input {
        width: 200px;
      }
    }
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.announcement-detail {
  padding: 20px;
  background-color: #f9f9f9;
  
  .detail-section {
    margin-bottom: 20px;
    
    h4 {
      margin-top: 0;
      margin-bottom: 15px;
      color: var(--el-color-primary);
      font-weight: 600;
      border-bottom: 1px solid var(--el-border-color-light);
      padding-bottom: 8px;
    }
    
    .detail-item {
      margin-bottom: 10px;
      line-height: 1.5;
      
      :deep(p) {
        margin: 8px 0;
      }
    }
  }
}
</style> 